# -*- coding: utf-8 -*-
"""
数据库建立和数据导入脚本
仅完成：1. 建立数据库表 2. 导入指定Excel文件
"""

import sys
from pathlib import Path

# 将项目根目录添加到路径
project_root = Path(__file__).resolve().parent
sys.path.insert(0, str(project_root))

def main():
    print("=" * 60)
    print("水库调度规程数据库建立和导入工具")
    print("=" * 60)
    
    # 导入必要的模块
    try:
        from D_db.io.importer import QAImporter
        from D_db.core.config import RESERVOIR_MAPPING
    except ImportError as e:
        print(f"导入模块失败: {e}")
        print("请先安装依赖: pip install -r requirements.txt")
        return
    
    # 指定Excel文件路径
    excel_file = project_root / "C_filter" / "QA_final" / "大伙房水库调度规程.xlsx"
    
    if not excel_file.exists():
        print(f"错误: 文件不存在 - {excel_file}")
        return
    
    print(f"\n目标文件: {excel_file}")
    print(f"文件大小: {excel_file.stat().st_size / 1024:.2f} KB")
    
    # 获取category_id
    file_name = excel_file.stem  # "大伙房水库调度规程"
    category_id = RESERVOIR_MAPPING.get(file_name)
    
    if not category_id:
        print(f"错误: 未找到'{file_name}'对应的category_id")
        print(f"可用的水库: {list(RESERVOIR_MAPPING.keys())}")
        return
    
    print(f"水库名称: {file_name}")
    print(f"Category ID: {category_id}")
    
    # 创建导入器
    importer = QAImporter()
    
    try:
        print("\n" + "=" * 60)
        print("步骤1: 连接数据库")
        print("=" * 60)
        importer.db_manager.connect()
        print("✓ 数据库连接成功")
        
        print("\n" + "=" * 60)
        print("步骤2: 创建数据库表")
        print("=" * 60)
        importer.db_manager.create_table()
        print("✓ 数据库表创建成功")
        
        print("\n" + "=" * 60)
        print("步骤3: 导入Excel数据")
        print("=" * 60)
        success = importer.import_qa_from_excel(str(excel_file), category_id)
        
        if success:
            print("\n" + "=" * 60)
            print("✓ 所有步骤完成！")
            print("=" * 60)
            print(f"数据库: QA_knowledge")
            print(f"表名: qa_knowledge")
            print(f"已导入文件: {file_name}.xlsx")
        else:
            print("\n✗ 数据导入失败")
            
    except Exception as e:
        print(f"\n✗ 执行失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        importer.db_manager.close()
        print("\n数据库连接已关闭")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n程序被用户中断")
    except Exception as e:
        print(f"\n程序执行出错: {e}")
        import traceback
        traceback.print_exc()

